import http.client
import json
import logging
from hashlib import md5
from io import StringIO
from random import randint
from urllib.error import URLError
from urllib.parse import urlencode

md5_digest_generator_proto = md5()

SMS_SERVER = '106.ihuyi.com'
SMS_URL = '/webservice/sms.php?method=Submit'
MSG_TEMPLATE = '您的验证码是：%s。请不要把验证码泄露给其他人。'


def to_md5_hex(origin_str):
    generator = md5_digest_generator_proto.copy()
    generator.update(origin_str.encode('utf-8'))
    return generator.hexdigest()


def gen_mobile_code(length=6):
    code = StringIO()
    for _ in range(length):
        code.write(str(randint(0, 9)))
    return code.getvalue()


"""
def send_short_message(mobile, code):
    params = urlencode({
        'account': 'C11691813',
        'password': '74968e3779b79784dfe63417e93b4d9b',
        'content': MSG_TEMPLATE % code,
        'mobile': mobile,
        'format': 'json'
    })
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/plain'
    }
    conn = http.client.HTTPConnection(SMS_SERVER, port=80, timeout=10)
    try:
        conn.request('POST', SMS_URL, params, headers)
        json_str = conn.getresponse().read().decode('utf-8')
        return json.loads(json_str)
    except URLError or KeyError as e:
        logging.error(e)
        return json.dumps({
            'code': 500,
            'msg': '短信服务暂时无法使用'
        })
    finally:
        conn.close()


if __name__ == '__main__':
    result = send_short_message('13548041193', gen_mobile_code())
    print(result)
"""
